package paidaxing.blog.post.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程池
 *
 * @author heefM
 * @date 2025-10-21
 */
@Component("postThreadPoolConfig")
@Configuration
public class ThreadPoolConfig {

    /**
     * 自定义线程池
     */
    ThreadPoolExecutor demoThreadPool=new ThreadPoolExecutor(
            10,
            20,
            30,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(200),
            new CustomThreadFactory("demo"),
            new ThreadPoolExecutor.DiscardOldestPolicy()
    );

    /**
     * 交给spring管理
     * @return
     */
    @Bean("demoThreadPool")
    public ThreadPoolExecutor demoThreadPool(){
        return demoThreadPool;
    }



    /**
     * 自定义线程工厂
     */
    static class CustomThreadFactory implements ThreadFactory {
        private final String namePrefix;
        private final AtomicInteger threadNumber = new AtomicInteger(1);

        public CustomThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix;
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, namePrefix + "-thread-" + threadNumber.getAndIncrement());
            thread.setDaemon(false);
            thread.setPriority(Thread.NORM_PRIORITY);
            return thread;
        }
    }


    /**
     * 自定义拒绝策略
     */
    static class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            // 记录被拒绝的任务信息
            System.err.println("Task rejected from " + executor.toString());
            
            // 尝试将任务添加到队列头部
            if (!executor.isShutdown()) {
                try {
                    executor.getQueue().put(r);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }


}